import request from '@/utils/request'
import {ILoginPayload} from "@/stores/actions/loginActions";
import {API} from "@/services/typing";
import {clearLStorage, clearSStorage, removeExpiresIn, removeRefreshToken, removeToken} from "@/utils/auth";
import {message} from "antd";

// 登录方法
export function login({username, password, code, uuid}: ILoginPayload, options?: Record<string, any>) {
    return request<API.LoginResult>({
        url: '/auth/login',
        headers: {
            isToken: false,
            repeatSubmit: false
        },
        method: 'POST',
        data: {username, password, code, uuid},
        ...(options || {}),
    })
}

// 注册方法
export function register(data) {
    return request({
        url: '/auth/register',
        headers: {
            isToken: false
        },
        method: 'POST',
        data: data
    })
}

// 刷新方法
export function refreshToken() {
    return request({
        url: '/auth/refresh',
        method: 'POST'
    })
}

// 获取用户详细信息
export function getInfo() {
    return request({
        url: '/system/user/getInfo',
        method: 'get'
    })
}

// 退出方法
export function logout() {
    return request({
        url: '/auth/logout',
        method: 'delete',
    })
}

export const handleLogout = async (showMessage?: boolean) => {
    const res = await logout() as any;
    if (res.code === 200) {
        removeToken()
        removeRefreshToken()
        removeExpiresIn()
        clearSStorage()
        clearLStorage()
        const {search, pathname} = window.location;
        const urlParams = new URL(window.location.href).searchParams;
        /** 此方法会跳转到 redirect 参数所在的位置 */
        const redirect = urlParams.get('redirect');
        // Note: There may be security issues, please note
        if (window.location.pathname !== '/login' && !redirect) {
            if (showMessage) {
                message.success('登出成功！')
            }
            window.location.replace(`${process.env.PUBLIC_URL}/login?redirect=${pathname + search}`)
        }
    }
}

// 获取验证码
export async function getCaptchaImg(params?: Record<string, any>, options?: Record<string, any>) {
    return await request('/code', {
        method: 'GET',
        params: {
            ...params,
        },
        headers: {
            isToken: false,
        },
        ...(options || {}),
    });
}


export async function getFakeCaptcha(
    // 叠加生成的Param类型 (非body参数swagger默认没有生成对象)
    params: API.getFakeCaptchaParams,
    options?: { [key: string]: any },
) {
    return request<API.FakeCaptcha>('/login/captcha', {
        method: 'POST',
        params: {
            ...params,
        },
        ...(options || {}),
    });
}
